import { IOperationNode } from './operation-node';
import { ITreeNode } from './tree-node';
import { ExecuteNode } from './execute-node';
import { SwitchNode } from './switch-node';

export class Extension implements ITreeNode {
    get data(): { id: string; name: string; } {
        let name: string;
        switch (this.type) {
            case 'InsertBefore':
                name = '操作前扩展';
                break;
            case 'Replace':
                name = '操作替换';
                break;
            case 'InsertAfter':
                name = '操作后扩展';
                break;
            default:
            // break;
        }
        return { id: this.id, name: name };
    }

    get children(): ITreeNode[] {
        return this.tasks;
    }

    isEditing: boolean;

    id: string;
    position: string;
    type: 'InsertBefore' | 'Replace' | 'InsertAfter'; // string;
    tasks: Array<IOperationNode & ITreeNode>;

    root: ITreeNode;

    constructor(extensionJson?: any) {
        if (extensionJson) {
            this.parse(extensionJson);
        }
    }

    parse(extensionJson: any) {
        const positionJson = extensionJson.position;
        if (positionJson) {
            if (positionJson instanceof Array) {
                this.position = positionJson[positionJson.length - 1];
            } else if (typeof positionJson === 'string') {
                this.position = positionJson;
            }
        }
        this.type = extensionJson.type;
        // extension 没有id  拼一个上去，否则树节点展示会有问题
        this.id = this.type + this.position;
        this.tasks = new Array();
        for (const taskJson of extensionJson.tasks) {
            if (!taskJson.type) {
                console.warn(`步骤节点信息不完整，跳过处理该节点。节点id：｛${taskJson.id}｝`);
                continue; // 没有type节点，信息不完整，跳过处理
            }

            switch (taskJson.type) {
                case 'executeNode':
                    this.tasks.push(new ExecuteNode(taskJson, this));
                    break;
                case 'switchNode':
                    this.tasks.push(new SwitchNode(taskJson, this));
                    break;
                default:
                    break;
            }
        }
    }

    toJson() {
        const result = {
            position: this.position,
            type: this.type,
            tasks: []
        };

        // task
        for (const task of this.tasks) {
            result.tasks.push(task.toJson());
        }
        return result;
    }
}
